package com.wonders.frame.autoGeneration.service;

import com.wonders.frame.autoGeneration.support.TaskContent;
import com.wonders.frame.autoGeneration.support.enums.ExecutorServiceEnum;
import com.wonders.frame.autoGeneration.support.from.GenForm;
import com.wonders.frame.autoGeneration.task.Core.Task;
import org.springframework.stereotype.Service;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 顾乘瑞
 */
@Service
public class AutoGenerationService {

    private static final String[] TASKS = {
            "com.wonders.frame.autoGeneration.task.GenControllerTask",
            "com.wonders.frame.autoGeneration.task.GenCssTask",
            "com.wonders.frame.autoGeneration.task.GenEntityTask",
            "com.wonders.frame.autoGeneration.task.GenJsxTask",
            "com.wonders.frame.autoGeneration.task.GenRepositoryTask",
            "com.wonders.frame.autoGeneration.task.GenServiceTask",
            "com.wonders.frame.autoGeneration.task.GenFormTask"
    };

    public void autoGeneration(GenForm form) {
        List<Task> actions = buildAction(form);
        try {
            ExecutorServiceEnum.execute(actions);
        } catch (InterruptedException e) {
            //TODO do something
        }

    }

    private List<Task> buildAction(GenForm form) {
        List<Task> actions = new ArrayList<>();
        Task task;
        final TaskContent cont = buildTaskContent(form);
        for (int i = 0; i < TASKS.length; i++) {
            try {
                Class<? extends Task> actionClazz = (Class<? extends Task>) Class.forName(TASKS[i]);
                Constructor<? extends Task> constructor = actionClazz.getConstructor(TaskContent.class);
                task = constructor.newInstance(cont);
                actions.add(task);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return actions;
    }

    private TaskContent buildTaskContent(GenForm form) {
        TaskContent cont = new TaskContent();
        cont.setTableName(form.getTableName());
        cont.setListForm(form.getListColumn());
        cont.setColumns(form.getTableColumn());

        cont.setAddForm(form.getAddColumn());
        cont.setSearchForm(form.getSearchColumn());
        return cont;
    }
}
